<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    一文看懂Python列表、元组和字符串操作.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-develop/一文看懂Python列表、元组和字符串操作"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  一文看懂Python列表、元组和字符串操作.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/develop/%E4%B8%80%E6%96%87%E7%9C%8B%E6%87%82Python%E5%88%97%E8%A1%A8%E3%80%81%E5%85%83%E7%BB%84%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%93%8D%E4%BD%9C/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/develop/">develop</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.9k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">12 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="一文看懂Python列表、元组和字符串操作"><a href="#一文看懂Python列表、元组和字符串操作" class="headerlink" title="一文看懂Python列表、元组和字符串操作"></a>一文看懂Python列表、元组和字符串操作</h1><h1 id="1-列表"><a href="#1-列表" class="headerlink" title="1 列表"></a>1 列表</h1><p>列表（List）是Python中非常重要的内置数据类型。列表由一系列元素组成，所有的元组被包含在一对方括号中。列表被创建将后，可以执行添加、删除、修改操作。</p>
<p>列表中可包含任意的Python数据信息，如字符串、数字、列表、元组等。<br><img src="http://iubest.gitee.io/pic/2020111101.png"></p>
<h2 id="1-1-列表介绍"><a href="#1-1-列表介绍" class="headerlink" title="1.1 列表介绍"></a>1.1 列表介绍</h2><p>列表是有序集合，没有固定大小，能够保存任意数量任意类型的 Python 对象，语法为 <code>[元素1, 元素2, ..., 元素n]</code>。</p>
<p>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; list &#x3D; [ “a”, “b”, “c” ]，定义字符列表。  </span><br><span class="line">&gt;&gt;&gt; list &#x3D; [ 1, 2, 3, 4 ]，定义数字列表。  </span><br><span class="line">&gt;&gt;&gt; list &#x3D; [ [1,2,3,4], [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] ]，定义列表的列表。  </span><br><span class="line">&gt;&gt;&gt; list &#x3D; [ (1,2,3,4), (&quot;a&quot;,&quot;b&quot;,&quot;c&quot;) ]，定义元组列表。  </span><br><span class="line">&gt;&gt;&gt; list((1,2))把一个元组转换成一个列表[1,2]， list(&#39;test&#39;)可把  </span><br><span class="line">字符串转换成[&#39;t&#39;,&#39;e&#39;,&#39;s&#39;,&#39;t&#39;]列表</span><br></pre></td></tr></table></figure>

<p>列表须知：</p>
<blockquote>
<ul>
<li><p>列表内元素的个数及元素的值可以改变；</p>
</li>
<li><p>列表内元素用中括号（[]）包裹；</p>
</li>
<li><p>列表内不同元素之间采用逗号（,）分隔；</p>
</li>
<li><p>列表内可以包含任何数据类型，也可以包括另一个列表；</p>
</li>
<li><p>列表可以通过序号来访问其中的成员；</p>
</li>
<li><p>可以对列表进行插入、删除、排序，修改列表中某元素等操作。</p>
</li>
</ul>
</blockquote>
<h2 id="1-2-列表操作"><a href="#1-2-列表操作" class="headerlink" title="1.2 列表操作"></a>1.2 列表操作</h2><p>列表的所有操作如下表所示：<br><img src="http://iubest.gitee.io/pic/2020111102.png"></p>
<h3 id="1-2-1-列表脚本操作符"><a href="#1-2-1-列表脚本操作符" class="headerlink" title="1.2.1 列表脚本操作符"></a>1.2.1 列表脚本操作符</h3><p>列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表，* 号用于重复列表。<img src="http://iubest.gitee.io/pic/2020111103.png"></p>
<h3 id="1-2-2-列表切片"><a href="#1-2-2-列表切片" class="headerlink" title="1.2.2 列表切片"></a>1.2.2 列表切片</h3><p>切片操作（slice）可以从一个列表中获取子列表（列表的一部分）。我们使用一对方括号、起始偏移量start、终止偏移量end 以及可选的步长step 来定义一个分片。<br><img src="http://iubest.gitee.io/pic/2020111104.png"></p>
<blockquote>
<p>格式：[start: end: step]<br>• [:] 提取从开头（默认位置0）到结尾（默认位置-1）的整个字符串<br>• [start:] 从start 提取到结尾<br>• [:end] 从开头提取到end - 1<br>• [start: end] 从start 提取到end - 1<br>• [start: end: step] 从start 提取到end - 1，每step 个字符提取一个<br>• 左侧第一个字符的位置/偏移量为0，右侧最后一个字符的位置/偏移量为-1</p>
</blockquote>
<p>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; list &#x3D; [1, 2, 3, 4, 5, 6, 7]  </span><br><span class="line">&gt;&gt;&gt; list[1:] #列出索引1以后的---------[2, 3, 4, 5, 6, 7]  </span><br><span class="line">&gt;&gt;&gt; list[:-1] #列出索引-1之前的-------[1, 2, 3, 4, 5, 6]  </span><br><span class="line">&gt;&gt;&gt; list[1:3] #列出索引1到3之间的-----[2]  </span><br><span class="line">&gt;&gt;&gt; list[::-1]#[7, 6, 5, 4, 3, 2, 1] #形成reverse函数的效果:</span><br></pre></td></tr></table></figure>

<h3 id="1-2-3-浅拷贝和深拷贝"><a href="#1-2-3-浅拷贝和深拷贝" class="headerlink" title="1.2.3 浅拷贝和深拷贝"></a>1.2.3 浅拷贝和深拷贝</h3><ul>
<li><p>浅拷贝：浅拷贝意味着构造一个新的集合对象，然后用原始对象中找到的子对象的引用来填充它。从本质上讲，浅层的复制只有一层的深度。复制过程不会递归，因此不会创建子对象本身的副本。</p>
</li>
<li><p>深拷贝：深拷贝使复制过程递归。这意味着首先构造一个新的集合对象，然后递归地用在原始对象中找到的子对象的副本填充它。以这种方式复制一个对象，遍历整个对象树，以创建原始对象及其所有子对象的完全独立的克隆。</p>
</li>
</ul>
<p>A. 赋值引用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a &#x3D; &#123;1:[1,2,3]&#125;  </span><br><span class="line">b &#x3D; a  </span><br><span class="line">print(id(a) &#x3D;&#x3D; id(b))</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">True</span><br></pre></td></tr></table></figure>

<p>赋值引用，a 和 b 都指向同一个对象。<br><img src="http://iubest.gitee.io/pic/2020111105.png"></p>
<p>B. 浅拷贝</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a &#x3D; &#123;1:[1,2,3]&#125;  </span><br><span class="line">b &#x3D; a.copy()  </span><br><span class="line">print(id(a) &#x3D;&#x3D; id(b))  </span><br><span class="line">print(id(a[1]) &#x3D;&#x3D; id(b[1]))</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">False  </span><br><span class="line">True</span><br></pre></td></tr></table></figure>

<p>a 和 b 是一个独立的对象，但他们的子对象还是指向统一对象（是引用）。<br><img src="http://iubest.gitee.io/pic/2020111106.png"><br>C. 深度拷贝</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">import copy  </span><br><span class="line">a &#x3D; &#123;1:[1,2,3]&#125;  </span><br><span class="line">b &#x3D; copy.deepcopy(a)  </span><br><span class="line">print(id(a) &#x3D;&#x3D; id(b))  </span><br><span class="line">print(id(a[1]) &#x3D;&#x3D; id(b[1]))  </span><br><span class="line">print(id(a[1][0]) &#x3D;&#x3D; id(b[1][0]))</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">False  </span><br><span class="line">False  </span><br><span class="line">True</span><br></pre></td></tr></table></figure>

<p>a 和 b 完全拷贝了父对象及其子对象，两者是完全独立的。对于a[1][0]和b[1][0]还是对于对象1的引用，并没有重新新建一个对象，这符合python的存储机制。<br><img src="http://iubest.gitee.io/pic/2020111107.png"></p>
<h3 id="1-2-4-其他常用操作"><a href="#1-2-4-其他常用操作" class="headerlink" title="1.2.4 其他常用操作"></a>1.2.4 其他常用操作</h3><p>-—– 列表排序：<br>注意排序优先级：数字&gt;大写字母&gt;小写字母&gt;符号&gt;中文<br>Python list内置sort() 方法用来排序，也可以使用Python内置的全局sorted() 方法对可迭代的序列排序生成新的序列。</p>
<ul>
<li><p>永久性排序：sort()<br><code>list.sort(key=None, reverse=False)</code> 对原列表进行排序。<br><code>key</code> – 主要是用来进行比较的元素，只有一个参数，具体的函数的参数就是取自于可迭代对象中，指定可迭代对象中的一个元素来进行排序。<code>reverse</code> – 排序规则，<code>reverse = True</code> 降序， <code>reverse = False</code> 升序（默认）。该方法没有返回值，但是会对列表的对象进行排序。</p>
</li>
<li><p>临时性排序：sorted()<br>Python内置函数，</p>
</li>
<li><p>反转排序：reverse()</p>
</li>
</ul>
<p>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&#96;&gt;&gt;&gt; list1 &#x3D; [3, 5, 1, 6, 9]  </span><br><span class="line">&gt;&gt;&gt; lsit2 &#x3D; [3, 5, 1, 6, 9]  </span><br><span class="line">&gt;&gt;&gt; a &#x3D; list1.sort()   #永久性排序，就是这个列表就变了  </span><br><span class="line">&gt;&gt;&gt; print(a, l1)   </span><br><span class="line"># None [1, 3, 5, 6, 9]  </span><br><span class="line">      </span><br><span class="line">&gt;&gt;&gt; b &#x3D;sorted(list1)    #临时性排序，就是可以赋值某个变量  </span><br><span class="line">&gt;&gt;&gt; print(b, list1)  </span><br><span class="line"># [1, 3, 5, 6, 9] [3, 5, 1, 6, 9]  </span><br><span class="line">  </span><br><span class="line">&gt;&gt;&gt; c &#x3D; list2.reverse()  </span><br><span class="line">&gt;&gt;&gt; print(c, list2)  </span><br><span class="line"># None [9, 6, 1, 5, 3]&#96;</span><br><span class="line"></span><br><span class="line">  </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>-—– list中的append和extend的区别：</p>
<ul>
<li><p>list.append(object) 向列表中添加一个对象object</p>
</li>
<li><p>list.extend(sequence) 把一个序列seq的内容添加到列表中</p>
</li>
</ul>
<h1 id="2-元组"><a href="#2-元组" class="headerlink" title="2 元组"></a>2 元组</h1><h2 id="2-1-元组操作"><a href="#2-1-元组操作" class="headerlink" title="2.1 元组操作"></a>2.1 元组操作</h2><p>Python 的元组与列表类似，不同之处在于tuple被创建后就不能对其进行修改，类似字符串。</p>
<ul>
<li><p>元组使用小括号，列表使用方括号。</p>
</li>
<li><p>元组可以使用在不希望数据被其他操作改变的场合。<br><img src="http://iubest.gitee.io/pic/2020111108.png"></p>
</li>
</ul>
<h2 id="2-2-解压元组"><a href="#2-2-解压元组" class="headerlink" title="2.2 解压元组"></a>2.2 解压元组</h2><p>解压（unpack）一维元组（有几个元素左边括号定义几个变量）<br>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(a, b, c)  &#x3D; (1, 10.31, &#39;python&#39;)  </span><br><span class="line">print(a, b, c)  </span><br><span class="line"># 1 10.31 python</span><br></pre></td></tr></table></figure>

<p>解压二维元组（按照元组里的元组结构来定义变量）<br>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">t &#x3D; (1, 10.31, (&#39;OK&#39;, &#39;python&#39;))  </span><br><span class="line">(a, b, (c, d)) &#x3D; t  </span><br><span class="line">print(a, b, c, d)  </span><br><span class="line"># 1 10.31 OK python</span><br></pre></td></tr></table></figure>

<p>如果你只想要元组其中几个元素，用通配符「*」，英文叫 wildcard，在计算机语言中代表一个或多个元素。下例就是把多个元素丢给了 <code>rest</code> 变量。<br>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">t &#x3D; 1, 2, 3, 4, 5  </span><br><span class="line">a, b, *rest, c &#x3D; t  </span><br><span class="line">print(a, b, c)  # 1 2 5  </span><br><span class="line">print(rest)  # [3, 4]</span><br></pre></td></tr></table></figure>

<p>如果你根本不在乎 rest 变量，那么就用通配符「*」加上下划线「_」。<br>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a, b, *_ &#x3D; t  </span><br><span class="line">print(a, b)  # 1 2</span><br></pre></td></tr></table></figure>

<h1 id="3-字符串"><a href="#3-字符串" class="headerlink" title="3 字符串"></a>3 字符串</h1><h2 id="3-1-字符串介绍"><a href="#3-1-字符串介绍" class="headerlink" title="3.1 字符串介绍"></a>3.1 字符串介绍</h2><p>字符串的定义：<br>字符串为引号之间的字符集合，这里引号包括单引号、双引号，三引号（三个连续的单引号或双引号）。</p>
<p>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; s1&#x3D;&#39;I love Python&#39;  </span><br><span class="line">&gt;&gt;&gt; s1  </span><br><span class="line">&#39;I love Python&#39;  </span><br><span class="line">  </span><br><span class="line">&gt;&gt;&gt; s2&#x3D;str([1,2,3])  </span><br><span class="line">&gt;&gt;&gt; s2  </span><br><span class="line">&#39;[1, 2, 3]&#39; </span><br></pre></td></tr></table></figure>

<p>Python的转义字符  </p>
<p>字符串前加 u、r、b</p>
<ul>
<li><p>u”中文字符组成的字符串”<br>作用：以 Unicode 格式 进行编码，一般用在中文字符串前面，防止因为源码储存格式问题，导致再次使用时出现乱码。</p>
</li>
<li><p>r”\n\n\n\n”　　# 表示一个普通生字符串 \n\n\n\n，而不表示换行<br>作用：去掉反斜杠的转义机制，常用于正则表达式，对应着re模块。</p>
</li>
<li><p>b’Hello World’   # 表示这是一个 bytes 对象<br>作用：b” “前缀表示：后面字符串是bytes 类型。在网络编程中，服务器和浏览器只认bytes 类型数据。在 Python3 中，bytes 和 str 的互相转换方式是str.encode(‘utf-8’)和bytes.decode(‘utf-8’)。</p>
</li>
</ul>
<h2 id="3-2-字符串格式化"><a href="#3-2-字符串格式化" class="headerlink" title="3.2 字符串格式化"></a>3.2 字符串格式化</h2><p>Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式，但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。在 Python 中，字符串格式化使用与 C 中 sprintf 函数一样的语法。<br>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#96;print &quot;My name is %s and weight is %d kg!&quot; % (&#39;Zara&#39;, 21)  </span><br><span class="line"># My name is Zara and weight is 21 kg!&#96;</span><br><span class="line"></span><br><span class="line">  </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>python 字符串格式化符号:<br><img src="http://iubest.gitee.io/pic/2020111110.png"><br>格式化操作符辅助指令：<br><img src="http://iubest.gitee.io/pic/2020111111.png"></p>
<h2 id="3-3-format-格式化函数"><a href="#3-3-format-格式化函数" class="headerlink" title="3.3 format 格式化函数"></a>3.3 format 格式化函数</h2><p>Python2.6 开始，新增了一种格式化字符串的函数 str.format()，它增强了字符串格式化的功能。</p>
<ul>
<li><p>基本语法是通过 {} 和 : 来代替以前的 % 。</p>
</li>
<li><p>format 函数可以接受不限个参数，位置可以不按顺序。</p>
</li>
</ul>
<p>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt;&quot;&#123;&#125; &#123;&#125;&quot;.format(&quot;hello&quot;, &quot;world&quot;)    # 不设置指定位置，按默认顺序  </span><br><span class="line">&#39;hello world&#39;  </span><br><span class="line">   </span><br><span class="line">&gt;&gt;&gt; &quot;&#123;0&#125; &#123;1&#125;&quot;.format(&quot;hello&quot;, &quot;world&quot;)  # 设置指定位置  </span><br><span class="line">&#39;hello world&#39;  </span><br><span class="line">   </span><br><span class="line">&gt;&gt;&gt; &quot;&#123;1&#125; &#123;0&#125; &#123;1&#125;&quot;.format(&quot;hello&quot;, &quot;world&quot;)  # 设置指定位置  </span><br><span class="line">&#39;world hello world&#39;</span><br></pre></td></tr></table></figure>

<ul>
<li>也可以设置参数：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">print(&quot;网站名：&#123;name&#125;, 地址 &#123;url&#125;&quot;.format())  </span><br><span class="line">   </span><br><span class="line"># 通过字典设置参数  </span><br><span class="line">site &#x3D; &#123;&quot;name&quot;: &quot;菜鸟教程&quot;, &quot;url&quot;: &quot;www.runoob.com&quot;&#125;  </span><br><span class="line">print(&quot;网站名：&#123;name&#125;, 地址 &#123;url&#125;&quot;.format(**site))  </span><br><span class="line">   </span><br><span class="line"># 通过列表索引设置参数  </span><br><span class="line">my_list &#x3D; [&#39;菜鸟教程&#39;, &#39;www.runoob.com&#39;]  </span><br><span class="line">print(&quot;网站名：&#123;0[0]&#125;, 地址 &#123;0[1]&#125;&quot;.format(my_list))  # &quot;0&quot; 是必须的</span><br></pre></td></tr></table></figure>

<p>数字格式化<br><img src="http://iubest.gitee.io/pic/2020111112.png"></p>
<blockquote>
<p>^, &lt;, &gt; 分别是居中、左对齐、右对齐，后面带宽度， : 号后面带填充的字符，只能是一个字符，不指定则默认是用空格填充。<br>+ 表示在正数前显示 +，负数前显示 -；（空格）表示在正数前加空格<br>b、d、o、x 分别是二进制、十进制、八进制、十六进制。</p>
</blockquote>
<p>【例子】</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; print(&quot;&#123;:.2f&#125;&quot;.format(3.1415926));  </span><br><span class="line">3.14  </span><br><span class="line">  </span><br><span class="line">&gt;&gt;&gt; print (&quot;&#123;&#125; 对应的位置是 &#123;&#123;0&#125;&#125;&quot;.format(&quot;runoob&quot;))  </span><br><span class="line">runoob 对应的位置是 &#123;0&#125;</span><br></pre></td></tr></table></figure>

<p>练习题：</p>
<p>1、<strong>列表操作练习</strong><br>列表lst 内容如下<br>lst = [2, 5, 6, 7, 8, 9, 2, 9, 9]<br>请写程序完成下列操作：</p>
<ol>
<li><p>在列表的末尾增加元素15</p>
</li>
<li><p>在列表的中间位置插入元素20</p>
</li>
<li><p>将列表[2, 5, 6]合并到lst中</p>
</li>
<li><p>移除列表中索引为3的元素</p>
</li>
<li><p>翻转列表里的所有元素</p>
</li>
<li><p>对列表里的元素进行排序，从小到大一次，从大到小一次</p>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; lst &#x3D; [2, 5, 6, 7, 8, 9, 2, 9, 9]  </span><br><span class="line">&gt;&gt;&gt; lst.append(15)  </span><br><span class="line">&gt;&gt;&gt; lst.insert(5,20)  </span><br><span class="line">&gt;&gt;&gt; lst.extend([2, 5, 6])  </span><br><span class="line">&gt;&gt;&gt; del lst[3]  </span><br><span class="line">&gt;&gt;&gt; lst.reverse()  </span><br><span class="line">&gt;&gt;&gt; lst.sort()  </span><br><span class="line">&gt;&gt;&gt; lst.sort(reverse&#x3D;True)</span><br></pre></td></tr></table></figure>

<p><strong>原文地址</strong></p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/OuDiShenmiss/article/details/107599379">https://blog.csdn.net/OuDiShenmiss/article/details/107599379</a></p>
<p><strong>相关阅读</strong>  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA4Nw==&mid=2247483689&idx=1&sn=3c6e345f0dc083450a034a292abcdcba&chksm=a73c6111904be8070fda0c5e64f9263193936aa9e80da13f0f8d77ad6559b431b4d576c0095c&scene=21#wechat_redirect">一文看懂Python面向对象编程(Python学习与新手入门必看)-绝对原创</a>  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA4Nw==&mid=2247484084&idx=1&sn=573989b9526aef01a3d515ab09afe86a&chksm=a73c628c904beb9a39adef9b95a1ce6560245b7f4e2a39207a55abc1a293935be203a35bcb13&scene=21#wechat_redirect">一文看懂Python多进程与多线程编程(工作学习面试必读)</a>  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA4Nw==&mid=2247484141&idx=1&sn=4a640751190159558bdb7db6d5b3d529&chksm=a73c62d5904bebc3a780224a2f6f1033a6ef8c1568f3a36585961d4d1fc3d3a942d31aa2e7fe&scene=21#wechat_redirect">一文看懂Python字典类型数据常见操作及排序</a>  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA4Nw==&mid=2247484195&idx=1&sn=0f92015bf28c53ad4ae48a5cc1d9e0da&chksm=a73c631b904bea0d17e994b76ddbb78b18a3bdada1162dfdec4f023efe3bd8bca4dfda13018f&scene=21#wechat_redirect">一文看懂Python系列之装饰器(decorator)(工作面试必读)</a>  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA4Nw==&mid=2247484163&idx=1&sn=a84fde69f4fb4d3ecab35856f8b71ca6&chksm=a73c633b904bea2d91564945bf51caa8131d8d65505d759ae0aa3a06074c6e7890e597eb48ff&scene=21#wechat_redirect">一文看懂Python的re模块及正则表达式(regex)</a>  </p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/develop/%E4%B8%80%E6%96%87%E7%9C%8B%E6%87%82Python%E5%88%97%E8%A1%A8%E3%80%81%E5%85%83%E7%BB%84%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%93%8D%E4%BD%9C/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/develop/" rel="tag">develop</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/develop/Python%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%8C%E5%B0%B1%E6%98%AF%E8%BF%99%E4%B9%88%E5%BC%BA%E5%A4%A7%EF%BC%81/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Python装饰器，就是这么强大！.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/develop/%E4%BD%BF%E7%94%A8%20IntelliJ%20IDEA%20%E6%9F%A5%E7%9C%8B%E7%B1%BB%E5%9B%BE%EF%BC%8C%E5%86%85%E5%AE%B9%E6%9E%81%E5%BA%A6%E8%88%92%E9%80%82/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">使用 IntelliJ IDEA 查看类图，内容极度舒适.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>